package app.itw.tison.cloud.utils;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


public class Md5Utils {


  private static byte[] md5(String s) throws NoSuchAlgorithmException {
    MessageDigest algorithm;
    algorithm = MessageDigest.getInstance("MD5");
    algorithm.reset();
    algorithm.update(s.getBytes(StandardCharsets.UTF_8));
    byte[] messageDigest = algorithm.digest();
    return messageDigest;
  }

  private static final String toHex(byte[] hash) {
    if (hash == null) {
      return null;
    }
    StringBuffer buf = new StringBuffer(hash.length * 2);
    int i;

    for (i = 0; i < hash.length; i++) {
      if ((hash[i] & 0xff) < 0x10) {
        buf.append("0");
      }
      buf.append(Long.toString(hash[i] & 0xff, 16));
    }
    return buf.toString();
  }

  public static String hash(String s) throws NoSuchAlgorithmException {
      return new String(toHex(md5(s)).getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8);
  }

  /**
   * 对密码按照用户名，密码，盐进行加密
   *
   * @param username 用户名
   * @param password 密码
   * @param salt 盐
   */
  public static String encryptPassword(String username, String password, String salt)
      throws NoSuchAlgorithmException {
    return Md5Utils.hash(username + password + salt);
  }

  /**
   * 对密码按照密码，盐进行加密
   *
   * @param password 密码
   * @param salt 盐
   */
  public static String encryptPassword(String password, String salt)
      throws NoSuchAlgorithmException {
    return Md5Utils.hash(password + salt);
  }
}